<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        p {
            width: 300px;
            height: 300px;
            background-color: #ccc;
        }
        p img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/190824/212516-1566653116f355.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/201228/214304-16091629844780.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/200618/005100-1592412660f973.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/180826/113958-1535254798fc1c.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/180315/110404-152108304476cb.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/170609/123945-14969831856c4d.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/200410/213246-1586525566e909.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/190917/183634-15687165942ef2.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/180803/084010-15332568109b5b.jpg" alt=""></p>
    <p><img src=""
            data-src="http://pic.netbian.com/uploads/allimg/190518/174718-15581728388724.jpg" alt=""></p>

</body>
<script>
    const imgs = document.querySelectorAll('p > img');
    // 视口高度
    let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    // 窗口滚动监听
    window.addEventListener('scroll', lazyLoad);
    // 页面加载完成执行
    window.addEventListener('load', lazyLoad);
    // 回调函数
    function lazyLoad() {
        // 滚动高度
        let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
        // 图片遍历
        imgs.forEach(img => {
            // 图片高度 < 视口高度 + 滚动高度，图片进入视口
            if (getOffsetTop(img) < clientHeight + scrollTop) {
                img.src = img.dataset.src;
            }
        });

        // 图片距离页面顶部距离
        function getOffsetTop(elem) {
            let pos = 0;
            while (elem) {
                pos += elem.offsetTop;
                elem = elem.offsetParent;
            }
            return pos;
        }
    }
</script>
</html>